<template>
  <div class="student-credits-container">
    <div class="header">
      <h2>学生学分统计</h2>
      <div class="header-buttons">
        <el-button type="primary" @click="loadData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出Excel
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="学号">
          <el-input
            v-model="searchForm.sno"
            placeholder="请输入学号"
            clearable
            style="width: 150px"
            @input="handleSearch"
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.sname"
            placeholder="请输入姓名"
            clearable
            style="width: 150px"
            @input="handleSearch"
          />
        </el-form-item>
        <el-form-item label="系名">
          <el-select
            v-model="searchForm.dept"
            placeholder="请选择系名"
            clearable
            style="width: 150px"
            @change="handleSearch"
          >
            <el-option
              v-for="dept in deptOptions"
              :key="dept"
              :label="dept"
              :value="dept"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学分获得率">
          <el-select
            v-model="searchForm.creditRateRange"
            placeholder="请选择范围"
            clearable
            style="width: 150px"
            @change="handleSearch"
          >
            <el-option label="优秀 (≥90%)" value="excellent" />
            <el-option label="良好 (80%-89%)" value="good" />
            <el-option label="及格 (60%-79%)" value="pass" />
            <el-option label="预警 (<60%)" value="warning" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table
        :data="filteredTableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        :default-sort="{ prop: 'sno', order: 'ascending' }"
      >
        <el-table-column prop="sno" label="学号" width="120" sortable />
        <el-table-column prop="sname" label="姓名" width="120" />
        <el-table-column prop="dept" label="系名" width="150" />
        <el-table-column prop="totalCourses" label="总选课门数" width="120" align="center" sortable />
        <el-table-column prop="totalCredits" label="总学分" width="100" align="center" sortable />
        <el-table-column v-if="SHOW_DETAILED_COLUMNS" prop="earnedCredits" label="已获得学分" width="120" align="center" sortable>
          <template #default="{ row }">
            <span :class="{ 'text-success': row.earnedCredits > 0 }">
              {{ row.earnedCredits }}
            </span>
          </template>
        </el-table-column>
        <el-table-column v-if="SHOW_DETAILED_COLUMNS" prop="unearnedCredits" label="未获得学分" width="120" align="center" sortable>
          <template #default="{ row }">
            <span :class="{ 'text-danger': row.unearnedCredits > 0 }">
              {{ row.unearnedCredits }}
            </span>
          </template>
        </el-table-column>
        <el-table-column v-if="SHOW_DETAILED_COLUMNS" prop="averageGrade" label="平均成绩" width="120" align="center" sortable>
          <template #default="{ row }">
            <span v-if="row.averageGrade > 0">
              {{ row.averageGrade.toFixed(2) }}
            </span>
            <span v-else class="text-muted">--</span>
          </template>
        </el-table-column>
        <el-table-column prop="creditRate" label="学分获得率" width="120" align="center" sortable>
          <template #default="{ row }">
            <el-tag
              :type="getCreditRateType(row.creditRate)"
              size="small"
            >
              {{ row.creditRate }}%
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="学习状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag
              :type="getStudyStatusType(row.creditRate)"
              size="small"
            >
              {{ getStudyStatusText(row.creditRate) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 筛选结果提示 -->
    <div v-if="isFiltered" class="filter-info">
      <el-alert
        :title="`当前显示 ${totalStudents} 条记录，共 ${tableData.length} 条记录`"
        type="info"
        :closable="false"
        show-icon
      />
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ totalStudents }}</div>
              <div class="stat-label">{{ isFiltered ? '筛选结果' : '总学生数' }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ averageCreditRate.toFixed(2) }}%</div>
              <div class="stat-label">平均学分获得率</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ excellentStudents }}</div>
              <div class="stat-label">优秀学生数 (≥90%)</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ riskStudents }}</div>
              <div class="stat-label">预警学生数 (<60%)</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Download } from '@element-plus/icons-vue'
import { studentApi } from '@/api'
import * as XLSX from 'xlsx'

// 控制变量 - 是否显示详细学分列
const SHOW_DETAILED_COLUMNS = false

// 响应式数据
const loading = ref(false)
const tableData = ref([])

// 搜索表单数据
const searchForm = ref({
  sno: '',
  sname: '',
  dept: '',
  creditRateRange: ''
})

// 计算属性
// 系名选项
const deptOptions = computed(() => {
  const depts = [...new Set(tableData.value.map(item => item.dept))]
  return depts.sort()
})

// 筛选后的数据
const filteredTableData = computed(() => {
  let filtered = tableData.value

  // 按学号筛选
  if (searchForm.value.sno) {
    filtered = filtered.filter(item => 
      item.sno.toLowerCase().includes(searchForm.value.sno.toLowerCase())
    )
  }

  // 按姓名筛选
  if (searchForm.value.sname) {
    filtered = filtered.filter(item => 
      item.sname.toLowerCase().includes(searchForm.value.sname.toLowerCase())
    )
  }

  // 按系名筛选
  if (searchForm.value.dept) {
    filtered = filtered.filter(item => item.dept === searchForm.value.dept)
  }

  // 按学分获得率范围筛选
  if (searchForm.value.creditRateRange) {
    switch (searchForm.value.creditRateRange) {
      case 'excellent':
        filtered = filtered.filter(item => item.creditRate >= 90)
        break
      case 'good':
        filtered = filtered.filter(item => item.creditRate >= 80 && item.creditRate < 90)
        break
      case 'pass':
        filtered = filtered.filter(item => item.creditRate >= 60 && item.creditRate < 80)
        break
      case 'warning':
        filtered = filtered.filter(item => item.creditRate < 60)
        break
    }
  }

  return filtered
})

const totalStudents = computed(() => filteredTableData.value.length)

const averageCreditRate = computed(() => {
  if (filteredTableData.value.length === 0) return 0
  const total = filteredTableData.value.reduce((sum, item) => sum + item.creditRate, 0)
  return total / filteredTableData.value.length
})

const excellentStudents = computed(() => {
  return filteredTableData.value.filter(item => item.creditRate >= 90).length
})

const riskStudents = computed(() => {
  return filteredTableData.value.filter(item => item.creditRate < 60).length
})

// 判断是否有筛选条件
const isFiltered = computed(() => {
  return searchForm.value.sno || 
         searchForm.value.sname || 
         searchForm.value.dept || 
         searchForm.value.creditRateRange
})

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const response = await studentApi.getStudentCreditsSummary()
    if (response.code === 200) {
      tableData.value = response.data || []
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(response.message || '数据加载失败')
    }
  } catch (error) {
    console.error('加载学分统计数据失败:', error)
    ElMessage.error('数据加载失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

const getCreditRateType = (rate) => {
  if (rate >= 90) return 'success'
  if (rate >= 80) return 'primary'
  if (rate >= 60) return 'warning'
  return 'danger'
}

const getStudyStatusType = (rate) => {
  if (rate >= 90) return 'success'
  if (rate >= 80) return 'primary'
  if (rate >= 60) return 'warning'
  return 'danger'
}

const getStudyStatusText = (rate) => {
  if (rate >= 90) return '优秀'
  if (rate >= 80) return '良好'
  if (rate >= 60) return '及格'
  return '预警'
}

// 搜索处理方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中实现，这里可以添加额外的处理逻辑
  // 例如：防抖处理、搜索统计等
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    sno: '',
    sname: '',
    dept: '',
    creditRateRange: ''
  }
}

// 导出Excel
const handleExport = () => {
  try {
    const exportData = filteredTableData.value.map(item => ({
      '学号': item.sno,
      '姓名': item.sname,
      '系名': item.dept,
      '总选课门数': item.totalCourses,
      '总学分': item.totalCredits,
      '学分获得率': item.creditRate + '%',
      '学习状态': getStudyStatusText(item.creditRate)
    }))
    
    const ws = XLSX.utils.json_to_sheet(exportData)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '学生学分统计')
    
    const fileName = `学生学分统计_${new Date().toISOString().slice(0, 10)}.xlsx`
    XLSX.writeFile(wb, fileName)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.student-credits-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.search-card .el-form {
  margin-bottom: 0;
}

.search-card .el-form-item {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.filter-info {
  margin-bottom: 20px;
}

.stats-cards {
  margin-top: 20px;
}

.stat-card {
  text-align: center;
  cursor: default;
}

.stat-item {
  padding: 10px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.text-success {
  color: #67C23A;
  font-weight: bold;
}

.text-danger {
  color: #F56C6C;
  font-weight: bold;
}

.text-muted {
  color: #C0C4CC;
}

/* 表格样式 - 统一对齐方式 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  text-align: left !important;
}

:deep(.el-table td) {
  text-align: left !important;
}

:deep(.el-table .cell) {
  text-align: left !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards .el-col {
    margin-bottom: 10px;
  }
  
  .stat-value {
    font-size: 24px;
  }
}
</style>